//
//  PTSimplePageBodyView.m
//  Pods
//
//  Created by aron on 2017/11/23.
//
//

#import "PTSimplePageBodyView.h"
#import "UIView+PTPageKit.h"

@interface PTSimplePageBodyView () <UIScrollViewDelegate>

@property (strong, nonatomic) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView* bgImageView;

@property (assign, nonatomic) BOOL loaded;
@property (strong, nonatomic) NSMutableDictionary *bodyDict;
@property (assign, nonatomic) NSInteger currentIndex;

@end

@implementation PTSimplePageBodyView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.bgImageView];
        [self addSubview:self.scrollView];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.scrollView.frame = CGRectMake(10, 20, self.bounds.size.width - 20, self.bounds.size.height - 30);
    self.bgImageView.frame = self.bounds;

    if (!self.loaded) {
        if (self.bodyDict && self.bodyDict.count > 0) {
            for (NSNumber *key in self.bodyDict) {
                UIViewController *viewController = [self.bodyDict objectForKey:key];
                if (viewController) {
                    [viewController.view removeFromSuperview];
                }
            }
            [self.bodyDict removeAllObjects];
        }
        NSInteger bodyCount = [self.dataSource numberOfItemsInBodyView:self];
        if (bodyCount <= 0) {
            return;
        }
        if (nil == self.bodyDict) {
            self.bodyDict = [[NSMutableDictionary alloc] initWithCapacity:bodyCount];
        }
        CGSize contentSize = CGSizeMake(bodyCount*self.width, 0);
        self.scrollView.contentSize = contentSize;
        self.currentIndex = 0;
        [self loadCurrentBody];
        self.loaded = YES;
    }
}


#pragma mark - ......::::::: Override :::::::......

- (void)reloadData {
    if (nil == self.dataSource) {
        return;
    }
    self.loaded = NO;
    [self setNeedsLayout];
}

- (void)moveToIndex:(NSInteger)index {
    NSInteger bodyCount = [self.dataSource numberOfItemsInBodyView:self];
    if (index < 0 || index >= bodyCount) {
        return;
    }
    self.currentIndex = index;
    [self loadCurrentBody];
}


#pragma mark - ......::::::: Private :::::::......

- (void)loadCurrentBody {
    [self.scrollView setContentOffset:CGPointMake(self.currentIndex*self.width, 0) animated:YES];
    
    UIViewController *viewController = [self.bodyDict objectForKey:[NSNumber numberWithInteger:self.currentIndex]];
    if (!viewController) {
        viewController = [self.dataSource bodyView:self viewControllerAtIndex:self.currentIndex];
    }
    if (!viewController) {
        return ;
    }
    
    [self.bodyDict setObject:viewController forKey:[NSNumber numberWithInteger:self.currentIndex]];
    [self addCurrentViewController:viewController];
    [self removeAllNearbyViewController];// 移除以触发controller生命周期切换及scrollsToTop事件传递
}

- (void)removeAllNearbyViewController {
    UIViewController *currentViewController = [self.bodyDict objectForKey:[NSNumber numberWithInteger:self.currentIndex]];
    NSInteger bodyCount = [self.dataSource numberOfItemsInBodyView:self];
    for (NSInteger i = 0; i < bodyCount; i++) {
        UIViewController *viewController = [self.bodyDict objectForKey:[NSNumber numberWithInteger:i]];
        if (viewController && viewController != currentViewController) {
            if (viewController.view.superview == self) {
                [self removeViewController:viewController];
            }
        }
    }
}

- (void)removeViewController:(UIViewController *)viewController {
    [viewController willMoveToParentViewController:nil];
    //    [viewController.view removeFromSuperview];
    [viewController removeFromParentViewController];
}

- (void)addCurrentViewController:(UIViewController *)viewController {
    [self addViewController:viewController index:self.currentIndex];
}

- (void)addViewController:(UIViewController *)viewController index:(NSInteger)index {
    [[self parentViewController] addChildViewController:viewController];
    viewController.view.frame = CGRectMake(index*self.width, 0, self.width, self.height);
    if (viewController.view.superview != self) {
        [self.scrollView addSubview:viewController.view];
    }
    [viewController didMoveToParentViewController:[self parentViewController]];
}

- (UIViewController*)parentViewController {
    UIResponder* responder = self;
    while (nil != responder && NO == [responder isKindOfClass:[UIViewController class]]) {
        responder = responder.nextResponder;
    }
    if ([responder isKindOfClass:[UIViewController class]]) {
        return (UIViewController*)responder;
    }
    return nil;
}

#pragma mark - ......::::::: Lazy load :::::::......

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
        _scrollView.scrollsToTop = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.scrollEnabled = NO;
        _scrollView.layer.cornerRadius = 20;
        _scrollView.layer.masksToBounds = YES;
        _scrollView.backgroundColor = [UIColor clearColor];
    }
    return _scrollView;
}

- (UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] init];
    }
    return _bgImageView;
}


#pragma mark - ......::::::: Public :::::::......

- (void)setupBgImage:(UIImage*)bgImage {
    self.bgImageView.image = bgImage;
}

@end
